/**
 * 主题工具函数
 * Theme Helper Utilities
 * 
 * 负责：
 * 1. 应用主题配置到 DOM
 * 2. 转换主题配置格式
 * 3. 验证主题配置有效性
 * 
 * @version 2.0
 */

/**
 * 应用主题配置到文档根元素
 * @param {Object} themeConfig - 主题配置对象
 * @returns {boolean} 是否应用成功
 */
export const applyTheme = (themeConfig) => {
  if (!themeConfig || typeof themeConfig !== 'object') {
    console.error('[ThemeHelper] 无效的主题配置:', themeConfig);
    return false;
  }

  try {
    const root = document.documentElement;
    
    // 遍历主题配置，设置 CSS 变量
    Object.entries(themeConfig).forEach(([key, value]) => {
      if (value && typeof value === 'string') {
        // 转换 key 格式：theme_bg_primary => --theme-bg-primary
        const cssVarName = `--${key.replace(/_/g, '-')}`;
        root.style.setProperty(cssVarName, value);
        
        // 调试日志
        // console.log(`[ThemeHelper] 设置 ${cssVarName} = ${value}`);
      }
    });

    console.log('[ThemeHelper] 主题配置已应用');
    return true;
  } catch (error) {
    console.error('[ThemeHelper] 应用主题配置失败:', error);
    return false;
  }
};

/**
 * 获取当前应用的主题配置
 * @returns {Object} 当前主题配置对象
 */
export const getCurrentTheme = () => {
  try {
    const root = document.documentElement;
    const computedStyle = getComputedStyle(root);
    
    const themeKeys = [
      'theme-bg-primary',
      'theme-bg-secondary',
      'theme-bg-card',
      'theme-bg-input',
      'theme-bg-bubble',
      'theme-text-primary',
      'theme-text-secondary',
      'theme-text-muted',
      'theme-text-dark',
      'theme-primary',
      'theme-primary-dark',
      'theme-secondary',
      'theme-accent',
      'theme-success',
      'theme-error',
      'theme-warning',
      'theme-accent-info',
      'theme-accent-danger',
      'theme-accent-warning',
      'theme-border-primary',
      'theme-border-secondary',
    ];

    const currentTheme = {};
    themeKeys.forEach(key => {
      const value = computedStyle.getPropertyValue(`--${key}`).trim();
      if (value) {
        currentTheme[key.replace(/-/g, '_')] = value;
      }
    });

    return currentTheme;
  } catch (error) {
    console.error('[ThemeHelper] 获取当前主题失败:', error);
    return {};
  }
};

/**
 * 重置主题为默认值
 */
export const resetTheme = () => {
  const defaultTheme = {
    theme_bg_primary: '#000000',
    theme_bg_secondary: '#121212',
    theme_bg_card: '#1C1C1E',
    theme_bg_input: '#2c2c2c',
    theme_bg_bubble: '#282828',
    theme_text_primary: '#ffffff',
    theme_text_secondary: '#E0E0E0',
    theme_text_muted: '#9e9e9e',
    theme_text_dark: '#4B4A4A',
    theme_primary: '#e91e63',
    theme_primary_dark: '#DB2777',
    theme_secondary: '#f7b356',
    theme_accent: '#F08A5D',
    theme_success: '#52C41A',
    theme_error: '#FF4D4F',
    theme_warning: '#FFB700',
    theme_accent_info: '#2196F3',
    theme_accent_danger: '#FF4D6A',
    theme_accent_warning: '#F9B872',
    theme_border_primary: '#333333',
    theme_border_secondary: '#2A2A2A',
  };

  applyTheme(defaultTheme);
  console.log('[ThemeHelper] 主题已重置为默认值');
};

/**
 * 验证颜色值是否有效
 * @param {string} color - 颜色值
 * @returns {boolean} 是否有效
 */
export const isValidColor = (color) => {
  if (!color || typeof color !== 'string') {
    return false;
  }

  // 支持十六进制颜色 (#RGB, #RRGGBB)
  const hexPattern = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
  if (hexPattern.test(color)) {
    return true;
  }

  // 支持 RGB/RGBA
  const rgbPattern = /^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*[\d.]+\s*)?\)$/;
  if (rgbPattern.test(color)) {
    return true;
  }

  // 支持 HSL/HSLA
  const hslPattern = /^hsla?\(\s*\d+\s*,\s*\d+%\s*,\s*\d+%\s*(,\s*[\d.]+\s*)?\)$/;
  if (hslPattern.test(color)) {
    return true;
  }

  return false;
};

/**
 * 清理主题配置（移除无效值）
 * @param {Object} themeConfig - 原始主题配置
 * @returns {Object} 清理后的主题配置
 */
export const sanitizeThemeConfig = (themeConfig) => {
  if (!themeConfig || typeof themeConfig !== 'object') {
    return {};
  }

  const sanitized = {};
  
  Object.entries(themeConfig).forEach(([key, value]) => {
    if (isValidColor(value)) {
      sanitized[key] = value;
    } else {
      console.warn(`[ThemeHelper] 跳过无效颜色值: ${key} = ${value}`);
    }
  });

  return sanitized;
};

/**
 * 合并主题配置（用新配置覆盖旧配置）
 * @param {Object} baseTheme - 基础主题配置
 * @param {Object} overrideTheme - 覆盖主题配置
 * @returns {Object} 合并后的主题配置
 */
export const mergeThemeConfig = (baseTheme, overrideTheme) => {
  return {
    ...baseTheme,
    ...overrideTheme,
  };
};

/**
 * 将主题配置转换为 CSS 字符串
 * @param {Object} themeConfig - 主题配置对象
 * @returns {string} CSS 字符串
 */
export const themeConfigToCss = (themeConfig) => {
  if (!themeConfig || typeof themeConfig !== 'object') {
    return '';
  }

  const cssLines = [':root {'];
  
  Object.entries(themeConfig).forEach(([key, value]) => {
    if (value) {
      const cssVarName = `--${key.replace(/_/g, '-')}`;
      cssLines.push(`  ${cssVarName}: ${value};`);
    }
  });
  
  cssLines.push('}');
  
  return cssLines.join('\n');
};

/**
 * 计算颜色的亮度
 * @param {string} color - 十六进制颜色值
 * @returns {number} 亮度值 (0-255)
 */
export const getColorBrightness = (color) => {
  if (!color || !color.startsWith('#')) {
    return 0;
  }

  // 移除 # 号
  let hex = color.substring(1);
  
  // 处理缩写形式 (#RGB => #RRGGBB)
  if (hex.length === 3) {
    hex = hex.split('').map(c => c + c).join('');
  }

  const r = parseInt(hex.substring(0, 2), 16);
  const g = parseInt(hex.substring(2, 4), 16);
  const b = parseInt(hex.substring(4, 6), 16);

  // 使用加权平均计算亮度
  return (r * 299 + g * 587 + b * 114) / 1000;
};

/**
 * 判断颜色是否为深色
 * @param {string} color - 十六进制颜色值
 * @returns {boolean} 是否为深色
 */
export const isDarkColor = (color) => {
  const brightness = getColorBrightness(color);
  return brightness < 128;
};

/**
 * 添加主题切换动画类
 */
export const addThemeTransition = () => {
  document.documentElement.classList.add('theme-transition');
};

/**
 * 移除主题切换动画类
 */
export const removeThemeTransition = () => {
  // 延迟移除，让过渡动画完成
  setTimeout(() => {
    document.documentElement.classList.remove('theme-transition');
  }, 300);
};

/**
 * 应用主题并带有过渡动画
 * @param {Object} themeConfig - 主题配置对象
 * @returns {Promise<boolean>} 是否应用成功
 */
export const applyThemeWithTransition = async (themeConfig) => {
  addThemeTransition();
  
  return new Promise((resolve) => {
    // 稍微延迟应用主题，确保过渡效果生效
    setTimeout(() => {
      const success = applyTheme(themeConfig);
      removeThemeTransition();
      resolve(success);
    }, 50);
  });
};

/**
 * 调试：打印当前所有CSS变量
 */
export const debugThemeVariables = () => {
  const root = document.documentElement;
  const computedStyle = getComputedStyle(root);
  
  console.group('[ThemeHelper] 当前CSS变量');
  
  // 获取所有CSS变量
  const allVars = {};
  for (let i = 0; i < document.styleSheets.length; i++) {
    try {
      const rules = document.styleSheets[i].cssRules;
      for (let j = 0; j < rules.length; j++) {
        const rule = rules[j];
        if (rule.selectorText === ':root') {
          const style = rule.style;
          for (let k = 0; k < style.length; k++) {
            const prop = style[k];
            if (prop.startsWith('--theme-')) {
              const value = style.getPropertyValue(prop);
              allVars[prop] = value;
            }
          }
        }
      }
    } catch (e) {
      // 跨域样式表会抛出异常，忽略
    }
  }

  console.table(allVars);
  console.groupEnd();
};

export default {
  applyTheme,
  getCurrentTheme,
  resetTheme,
  isValidColor,
  sanitizeThemeConfig,
  mergeThemeConfig,
  themeConfigToCss,
  getColorBrightness,
  isDarkColor,
  addThemeTransition,
  removeThemeTransition,
  applyThemeWithTransition,
  debugThemeVariables,
};

